import { checkPermission, isReadyPermission } from "@/helpers";
import { Directive } from "vue";
import router from "@/routes";
/*
 * @Description:
 * @Author: 胡涛
 * @Date: 2023-11-12 11:50:37
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-19 20:45:39
 */

/**
 *
 */
const authDirective: Directive = {
  /**
   * 或事件监听器应用前调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  created(el, binding, vnode, prevVnode) {
    // 下面会介绍各个参数的细节
    console.log("created - action", binding.value);
  },
  /**
   * 在元素被插入到 DOM 前调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  beforeMount(el, binding, vnode, prevVnode) {
    // console.log("beforeMount - action", binding.value);
  },
  /**
   * 在绑定元素的父组件 及他自己的所有子节点都挂载完成后调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  mounted(el, binding, vnode, prevVnode) {
    const meta = router.currentRoute.value.meta;
    const module = meta.permissionCode || "";
    const action = binding.value?.action || binding.value || "";
    const isFullName = action && action.indexOf(".") >= 0;
    const permissionName = isFullName ? action : [module, action].join(".");
    if (action && permissionName) {
      checkAction(el, permissionName);
    }
  },
  /**
   * 绑定元素的父组件更新前调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  beforeUpdate(el, binding, vnode, prevVnode) {
    // console.log("beforeUpdate - action", binding.value);
  },
  /**
   *  在绑定元素的父组件
   * 及他自己的所有子节点都更新后调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  updated(el, binding, vnode, prevVnode) {
    // console.log("updated - action", binding.value);
    let perms = "";
    let action: string = binding.value;
  },
  /**
   *  绑定元素的父组件卸载前调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  beforeUnmount(el, binding, vnode, prevVnode) {
    // console.log("beforeUnmount - action", binding.value);
  },
  /**
   * 绑定元素的父组件卸载后调用
   * @param el
   * @param binding
   * @param vnode
   * @param prevVnode
   */
  unmounted(el, binding, vnode, prevVnode) {
    // console.log("unmounted - action", binding.value);
  },
};

/**
 * 检查按钮权限
 * @param el
 * @param permissionName
 */
const checkAction = function (el: HTMLElement, permissionName: string) {
  if (isReadyPermission()) {
    if (!checkPermission(permissionName)) {
      el.style.display = "none";
    } else {
      el.style.display = "";
    }
  } else {
    setTimeout(checkAction, 100, el, permissionName);
  }
};

export { authDirective };
